'''
utility
Author: Alex Foran

Note: This file once contained a full XML parser, written from scratch... but was then replaced with a simple adaption after reading into built-in parsers. Let that serve as a lesson - remember to look at google results past the first one.
'''
import os,xml.dom.minidom

'''
Gets the position of an element in an array.

Params:
array - The array.
object - The element to be found.
'''
def getarrayposition(array,object):
	pos=-1
	for i in range(len(array)):
		if array[i]==object:
			pos=i
			break
	return pos

'''
Loads XML data from file, or returns None if the file does not exist.

Params:
filename - The path to the file.
'''
def loadXML(filename):
	if os.path.exists(filename):
		return XML(filename)
	else:
		return None

'''
Class for parsing and reading XML data.
'''
class XML:
	'''
	Constructor.
	
	Params:
	file - The filename to be loaded.
	parse - If True, the file will be loaded and parsed. Otherwise, merely the filename will be contained.
	'''
	def __init__(self,file,parse=True):
		self.filename=file
		self.xml=None
		if parse:
			file=open(file,'r')
			self.parse(file)
			file.close()
	
	'''
	Parses the file, storing the data internally.
	'''
	def parse(self,file):
		try:
			self.xml=xml.dom.minidom.parse(file)
		except Exception:
			print "XML parse error"
	
	'''
	Returns an XML-formatted version of the data represented by this object.
	'''
	def XML(self):
		if self.root!=None:
			return self.root.XML(0)
	
	'''
	Writes the supplied text into the stored file.
	
	Params:
	text - The text to be written.
	'''
	def save(self,text):
		fh=open(self.filename,'w')
		fh.write(text)
		fh.close()
	
	'''
	Returns all elements in the XML with a given node name.
	
	Params:
	name - The name to search for.
	'''
	def getElementsByTagName(self,name):
		return self.xml.getElementsByTagName(name)
